package com.manage.service;

import java.util.List;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.manage.dao.CourseRepository;
import com.manage.dao.TrainingCourseRepository;
import com.manage.entity.Course;
import com.manage.entity.TrainingCourse;

@Service
@Transactional
public class CourseService implements ICourseService{
	
	@Autowired
	private CourseRepository courseRepository;
	@Autowired
	private TrainingCourseRepository trainingCourseRepository;
	
	public void saveOrUpdate(Course course) {
		courseRepository.save(course);
	}
	
	public void delete(Long id) {
		List<TrainingCourse> tcList=trainingCourseRepository.findTrainCourse(id);
		if(tcList!=null) {
			for(TrainingCourse tc:tcList) {
				tc.setCourses(null);
				trainingCourseRepository.save(tc);
				
			}
		}
		courseRepository.delete(id);
	}
	
	public void delete(List<Long> ids) {
		for(Long id:ids) {
			List<TrainingCourse> tcList=trainingCourseRepository.findTrainCourse(id);		
			if(tcList!=null) {
				for(TrainingCourse tc:tcList) {
					tc.setCourses(null);
					trainingCourseRepository.save(tc);
					
				}
			}
			courseRepository.delete(id);
		}		
	}
	
	@Transactional(readOnly = true)
	public Course findOne(Long id) {
		return courseRepository.findOne(id);
	}
	
	@Transactional(readOnly = true)
	public List<Course> findAll(){
		return (List<Course>) courseRepository.findAll();
	}

	@Transactional(readOnly = true)
	public Page<Course> findAll(Specification<Course> spec, Pageable pageable){
		return courseRepository.findAll(spec, pageable);
	}

}
